package com.dhx.controller;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dhx.common.R;
import com.dhx.domain.Category;
import com.dhx.service.ICategoryService;
import com.dhx.service.impl.CategoryServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 菜品及套餐分类 前端控制器
 * </p>
 *
 * @author 邓鹄翔
 * @since 2022-03-08
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private ICategoryService categoryService;

    /**
     * 添加分类
     *
     * @param request
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Category category) {
        boolean save = categoryService.save(category);
        return R.success("新增分类成功");
    }

    /**
     * 分页
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);
        //使用lambda
        LambdaUpdateWrapper<Category> wrapper = new LambdaUpdateWrapper<>();
        //根据修改时间进行排序
        wrapper.orderByDesc(Category::getUpdateTime);
        //分页查询
        categoryService.page(pageInfo, wrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Category> getById(@PathVariable Long id) {
        Category byId = categoryService.getById(id);
        if (byId != null) {
            return R.success(byId);
        }
        return R.error("没有查询到信息");
    }

    /**
     * 修改
     *
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Category category) {
        boolean b = categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 删除
     *
     * @param
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long id) {
        categoryService.remove(id);
        return R.success("分类信息删除成功");
    }

    /**
     * 根据条件查询分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        LambdaUpdateWrapper<Category> wrapper = new LambdaUpdateWrapper<>();
        //添加条件
        wrapper.eq(category.getType() != null, Category::getType, category.getType());
        //先根据排序号排序，在根据修改时间查询
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }
}

